
package com.whwace.services.common;

import com.alibaba.fastjson.JSONObject;
import com.whwace.components.YkNacosHttpClient;
import com.whwace.core.BusinessContext;
import com.whwace.core.standard.ICoreService;
import com.whwace.entity.YkCloudApi;
import com.whwace.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.*;

/**
 * DESKTOP-MI3GDF5
 * 处理微服务
 */
@Slf4j
public class HandleCloudApiServiceSv implements ICoreService {

    @Autowired
    private YkNacosHttpClient ykNacosHttpClient;

    @Override
    public void execute(BusinessContext ctx) throws AppException {
        log.info("{}", "处理微服务");
        String transCode = ctx.getTransCode();
        List<String> transCodeSplit = new ArrayList<>(Arrays.asList(transCode.split("/")));
        YkCloudApi ykCloudApi = new YkCloudApi();
        ykCloudApi.setCloudServiceName(transCodeSplit.get(0));
        transCodeSplit.remove(0);
        ykCloudApi.setUrl(StringUtils.join(transCodeSplit, "/"));
        ykCloudApi.setHttpMethod(HttpMethod.valueOf(ctx.getRequest().getMethod()));
        ykCloudApi.setParams(ctx.getParams());
        ykCloudApi.setSerialNo(ctx.getYkLog4j2().getSerialNo());
        log.info("微服务信息：{}", JSONObject.toJSONString(ykCloudApi, true));
        //调用微服务
        ResponseEntity<Map<String, Object>> response = ykNacosHttpClient.exchange(ykCloudApi);
        log.info("微服务返回信息：{}", JSONObject.toJSONString(response, true));
        if (response.getStatusCode() != HttpStatus.OK) {
            throw new AppException("88x8888", "fetch microService " + ykCloudApi.getCloudServiceName() + " error:" + response.getBody());
        }
        Map<String, Object> body = response.getBody();
        if (StringUtils.equalsIgnoreCase(Objects.requireNonNull(response.getBody()).get("code").toString(), "00x0000")) {
            //正常返回
            body.remove("msg");
            body.remove("SerialNo");
            body.remove("code");
            ctx.putAll(body);
        } else if(StringUtils.equalsIgnoreCase(Objects.requireNonNull(response.getBody()).get("code").toString(), "99x9999")){
            //阻断性错误
            throw new AppException(body.get("code").toString(), body.get("msg").toString());
        }else{
            //非阻断性错误
            ctx.putAll(body);
        }
    }
}
    